/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.util;

import java.lang.reflect.AccessibleObject;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 3/6/2017
 */
public class SpringUtils {

    private static final String SPRING_PARAMETER_NAME_DISCOVERER_CLASS = "org.springframework.core.LocalVariableTableParameterNameDiscoverer";
    public static final String SPRING_BEAN_FACTORY_CLASS = "org.springframework.beans.factory.BeanFactory";
    private static final boolean springInClasspath;

    private static Object parameterNameDiscoverer;

    static {
        springInClasspath = ReflectionUtils.isPresent(SPRING_BEAN_FACTORY_CLASS);
        try {
            if (springInClasspath) {
                parameterNameDiscoverer = Class.forName(SPRING_PARAMETER_NAME_DISCOVERER_CLASS).newInstance();
            }
        } catch (ReflectiveOperationException e) {
            //ignored
        }
    }

    public static boolean isSpringInClasspath() {
        return springInClasspath;
    }

    public static Object getBean(Object beanFactory, String name) {
        try {
            return beanFactory.getClass().getDeclaredMethod("getBean", String.class).invoke(beanFactory, name);
        } catch (ReflectiveOperationException e) {
            return null;
        }
    }

    public static Object getBean(Object beanFactory, Class<?> clz) {
        try {
            return beanFactory.getClass().getDeclaredMethod("getBean", Class.class).invoke(beanFactory, clz);
        } catch (ReflectiveOperationException e) {
            return null;
        }
    }

    public static String[] getParameterNames(AccessibleObject accessible) {
        if(parameterNameDiscoverer == null || accessible == null) {
            return null;
        }
        try {
            return (String[])parameterNameDiscoverer.getClass().getDeclaredMethod("getParameterNames", accessible.getClass()).invoke(parameterNameDiscoverer, accessible);
        } catch (ReflectiveOperationException e) {
            return null;
        }
    }

}
